package org.veloxbot.api.internals.concurrent;

import java.util.List;
import java.util.ArrayList;

import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;

/**
 * @author Velox
 */
public class TaskExecutor {

	private static final ExecutorService executor = Executors.newCachedThreadPool();

	private static final List<LoopTask> looptasks = new ArrayList<LoopTask>();

	/**
	 * Submits the given Task to the executor.
	 *
	 * @param task The Task to submit.
	 */
	public static void submit(final Task task) {
		if (task instanceof LoopTask) {
			looptasks.add((LoopTask) task);
		}
		executor.submit(task);
	}

	/**
	 * Removes and stops the given Task from the executor.
	 *
	 * @param task The Task to remove from the executor.
	 */
	public static void revoke(final Task task) {
		if (task instanceof LoopTask) {
			final LoopTask looptask = ((LoopTask) task);
			if (looptasks.contains(looptask)) {
				looptasks.remove(looptask);
				looptask.terminate();
			}
		}
	}

	/**
	 * Terminates all tasks in the executor.
	 */
	public static void terminate() {
		executor.shutdown();
		for (final LoopTask looptask : looptasks) {
			looptask.terminate();
		}
	}

	/**
	 * Removes all tasks in the executor.
	 */
	public static void revokeAll() {
		for (final LoopTask looptask : looptasks) {
			looptask.terminate();
		}
		looptasks.removeAll(looptasks);
	}
}
